use crate::dto::ResObj;
use crate::utils::redis;
use hypers::prelude::{hook, Error, Next, Request, Responder, Response};
use hypers::serde_json::json;

#[hook]
pub async fn auth_token(mut req: Request, next: Next<'_>) -> Result<Response, Error> {
    if let Some(token) = req.headers().get("Authorization") {
        // 验证token
        match redis::get::<i32, &str>(&token.to_str().unwrap().to_string().replace("Bearer ", "")) {
            Err(_) => {
                return Err(Error::Response(
                    401,
                    json!(ResObj::<i32>::custom_code(401, "token无效".to_owned())),
                ));
            }
            Ok(user_id) => {
                // println!("有token---{}",user_id);
                req.insert("userId", user_id);
                return Ok(next.next(req).await);
            }
        }
    } else {
        return Err(Error::Response(
            401,
            json!(ResObj::<i32>::custom_code(401, "token无效".to_owned())),
        ));
    }
}
